package com.yzs.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzs.common.bean.R;
import com.yzs.entity.Admin;
import com.yzs.mapper.AdminMapper;
import com.yzs.service.IAdminService;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.MD5Util;
import com.yzs.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    AdminMapper mapper;
    @Autowired
    JwtUtil JwtUtil;
    @Override
    public R login(String username, String pwd) {
        Map<String, Object> map = new HashMap<>();
        //自定义查询
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username).eq("password", pwd);
        Admin admin = mapper.selectOne(wrapper);
        // 判断是否存在用户
        if (admin != null) {
            if ("冻结".equals(admin.getAdminStatus())){
                return R.error("登陆失败！用户已冻结！");
            }
            String token = JwtUtil.createToken(admin);
            if (token != null){
                map.clear();
                map.put("token", token);
                admin.setLoginTime(TimeUtil.getNowTime());
                mapper.updateById(admin);
                return R.ok("登录成功！", map);
            }else {
                return R.error("登陆失败！");
            }
        }
        return R.error("用户或密码错误！");

    }

    @Override
    public R<String> register(Admin admin) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", admin.getUsername());
        Admin hasAdmin = mapper.selectOne(wrapper);
        if (hasAdmin == null) {
            String nowTime = TimeUtil.getNowTime();
            admin.setPassword(MD5Util.GetMD5Code(admin.getPassword()));
            admin.setCreateTime(nowTime);
            admin.setRole("Admin");
            admin.setAdminStatus("冻结");
            if (mapper.insert(admin) == 1) {
                return R.ok("注册管理员成功！");
            }
        }
        return R.error("已存在该用户！注册失败！");
    }

    @Override
    public R getAdminById(Integer id) {
        Admin admin = mapper.selectById(id);
        admin.setPassword("");
        return R.ok(admin);
    }

    @Override
    public R getHouseAdminById(Integer id) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.select("name","phone").eq("id",id);
        Admin admin = mapper.selectOne(adminQueryWrapper);
        admin.setPassword("");
        return R.ok(admin);
    }


}
